<?php

namespace app\api\controller;

use app\common\controller\BasicApi;
use app\common\model\UserModel;
use app\common\model\CourseModel;
use app\common\model\UserSignInModel;

class Usersignin extends BasicApi
{
    protected $member;
    protected $openid;

    public function _initialize()
    {
        parent::_initialize();
        $this->openid = isset($this->header['token'])?$this->header['token']:'';
    }

    /**
     * 用户签到/签退
     */
    public function userSignIn()
    {
        $course_id = $this->request->post('course_id');
        $course_info = CourseModel::get($course_id);
        $user_info = $this->getMember();
        $data = array(
            'nickname' => $user_info['nickname'],
            'realname' => $user_info['realname'],
            'openid' => $user_info['openid'],

            'school_id' => $course_info['school_id'],
            'grade_id' => $course_info['grade_id'],
            'class_id' => $course_info['class_id'],
            'course_id' => $course_id,
            'course_name' => $course_info['name'],

            'image_url' => $this->request->post('iamge_url'),
            'type' => $this->request->post('type'),
            'date' => date('Y-m-d'),
//            'create_time' => time(),
        );
        $result = UserSignInModel::create($data);
        if($result){
            $this->success('签到/签退成功',$result,200);
        }
        $this->error('签到/签退异常，请重试');
    }

    /**
     * 获取用户签到/签退信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserSignInfo()
    {
        $course_id = $this->request->post('course_id');
        $date = date('Y-m-d');
        $signIn = UserSignInModel::where(['openid'=>$this->openid,'course_id'=>$course_id,  'date' => $date, 'type' => '1'])->order('create_time asc')->find();
        $signOut = UserSignInModel::where(['openid'=>$this->openid,'course_id'=>$course_id,  'date' => $date, 'type' => '2'])->order('create_time desc')->find();
        $this->success('',['sign_in'=>$signIn, 'sign_out'=>$signOut],200);
    }

    /**
     * 获取会员信息
     */
    protected function getMember()
    {
        return UserModel::where(['openid'=>$this->openid])->find();
    }
}